package com.andy.network.util

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.andy.network.entity.ApiResponse
import com.andy.network.entity.parseData
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * @creator:LuoFan
 * @date:2022/9/29
 * @description:
 */


fun <T> LifecycleOwner.collectHttp(
    data: StateFlow<ApiResponse<T>>,
    minActiveState: Lifecycle.State = Lifecycle.State.CREATED,
    listener:HttpListener<T>
): Job = lifecycleScope.launch {
    data.flowWithLifecycle(lifecycle, minActiveState).collect { result: ApiResponse<T> ->
        result.parseData(listener)
    }
}




